<template>
  <div class="login-page">
    <!-- 登录内容 -->
    <div class="container py-5">
      <div class="row justify-content-center">
        <!-- 登录区域 -->
        <div class="col-12 col-md-6 col-lg-5">
          <div class="login-container card">
            <div class="card-body p-5">
              <div class="text-center mb-4">
                <h3 class="card-title mb-3">欢迎回来</h3>
                <p class="text-muted">请登录您的账户</p>
              </div>

              <!-- 错误提示 -->
              <div v-if="error" class="alert alert-danger" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                {{ error }}
              </div>

              <!-- 登录表单 -->
              <form @submit.prevent="handleLogin" class="login-form">
                <div class="form-group mb-4">
                  <label for="account" class="form-label">
                    用户名 <span class="required">*</span>
                  </label>
                  <div class="input-group">
                    <span class="input-group-text">
                      <i class="fas fa-user"></i>
                    </span>
                    <input
                      id="account"
                      v-model="loginForm.account"
                      type="text"
                      class="form-control"
                      :class="{ 'is-invalid': errors.account }"
                      placeholder="请输入用户名"
                      required
                    />
                  </div>
                  <div v-if="errors.account" class="invalid-feedback d-block">
                    {{ errors.account }}
                  </div>
                </div>

                <div class="form-group mb-4">
                  <label for="password" class="form-label">
                    密码 <span class="required">*</span>
                  </label>
                  <div class="input-group">
                    <span class="input-group-text">
                      <i class="fas fa-lock"></i>
                    </span>
                    <input
                      id="password"
                      v-model="loginForm.password"
                      :type="showPassword ? 'text' : 'password'"
                      class="form-control"
                      :class="{ 'is-invalid': errors.password }"
                      placeholder="请输入密码"
                      required
                    />
                    <button
                      type="button"
                      class="btn btn-outline-secondary"
                      @click="showPassword = !showPassword"
                    >
                      <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                    </button>
                  </div>
                  <div v-if="errors.password" class="invalid-feedback d-block">
                    {{ errors.password }}
                  </div>
                </div>

                <button
                  type="submit"
                  class="btn btn-primary btn-lg w-100 mb-3"
                  :disabled="loading"
                >
                  <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="fas fa-sign-in-alt me-2"></i>
                  {{ loading ? '登录中...' : '登录' }}
                </button>

                <div class="text-center">
                  <a href="#" class="text-decoration-none text-muted small">
                    忘记密码？
                  </a>
                </div>
              </form>
            </div>
          </div>
        </div>

        <!-- 注册区域 -->
        <div class="col-12 col-md-6 col-lg-5">
          <div class="register-container card">
            <div class="card-body p-5">
              <div class="text-center mb-4">
                <h3 class="card-title mb-3">新用户注册</h3>
                <p class="text-muted">创建账户享受更快的结账体验</p>
              </div>

              <!-- 注册表单 -->
              <form @submit.prevent="handleRegister" class="register-form">
                <div class="form-group mb-4">
                  <label for="registerUsername" class="form-label">
                    用户名 <span class="required">*</span>
                  </label>
                  <div class="input-group">
                    <span class="input-group-text">
                      <i class="fas fa-user"></i>
                    </span>
                    <input
                      id="registerUsername"
                      v-model="registerForm.username"
                      type="text"
                      class="form-control"
                      :class="{ 'is-invalid': registerErrors.username }"
                      placeholder="请输入用户名"
                      required
                    />
                  </div>
                  <div v-if="registerErrors.username" class="invalid-feedback d-block">
                    {{ registerErrors.username }}
                  </div>
                </div>

                <div class="form-group mb-4">
                  <label for="registerPassword" class="form-label">
                    密码 <span class="required">*</span>
                  </label>
                  <div class="input-group">
                    <span class="input-group-text">
                      <i class="fas fa-lock"></i>
                    </span>
                    <input
                      id="registerPassword"
                      v-model="registerForm.password"
                      type="password"
                      class="form-control"
                      :class="{ 'is-invalid': registerErrors.password }"
                      placeholder="请输入密码"
                      required
                    />
                  </div>
                  <div v-if="registerErrors.password" class="invalid-feedback d-block">
                    {{ registerErrors.password }}
                  </div>
                </div>

                <div class="form-group mb-4">
                  <label for="confirmPassword" class="form-label">
                    确认密码 <span class="required">*</span>
                  </label>
                  <div class="input-group">
                    <span class="input-group-text">
                      <i class="fas fa-lock"></i>
                    </span>
                    <input
                      id="confirmPassword"
                      v-model="registerForm.checkPassword"
                      type="password"
                      class="form-control"
                      :class="{ 'is-invalid': registerErrors.checkPassword }"
                      placeholder="请确认密码"
                      required
                    />
                  </div>
                  <div v-if="registerErrors.checkPassword" class="invalid-feedback d-block">
                    {{ registerErrors.checkPassword }}
                  </div>
                </div>

                <button
                  type="submit"
                  class="btn btn-success btn-lg w-100 mb-3"
                  :disabled="registerLoading"
                >
                  <span v-if="registerLoading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="fas fa-user-plus me-2"></i>
                  {{ registerLoading ? '注册中...' : '创建账户' }}
                </button>

                <div class="text-center">
                  <small class="text-muted">
                    注册即表示您同意我们的
                    <a href="#" class="text-decoration-none">服务条款</a>
                    和
                    <a href="#" class="text-decoration-none">隐私政策</a>
                  </small>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { userRegister } from '@/api/user'
import { Message } from '@/utils/message'
import type { UserLoginRequest, UserRegisterRequest } from '@/types/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 登录表单
const loginForm = reactive<UserLoginRequest>({
  account: '',
  password: ''
})

// 注册表单
const registerForm = reactive<UserRegisterRequest>({
  username: '',
  password: '',
  checkPassword: ''
})

// 状态变量
const loading = ref(false)
const registerLoading = ref(false)
const showPassword = ref(false)
const rememberMe = ref(false)
const error = ref('')

// 表单验证错误
const errors = reactive({
  account: '',
  password: ''
})

const registerErrors = reactive({
  username: '',
  password: '',
  checkPassword: ''
})

// 表单验证
const validateLoginForm = () => {
  errors.account = ''
  errors.password = ''

  if (!loginForm.account.trim()) {
    errors.account = '请输入用户名'
    return false
  }

  if (!loginForm.password) {
    errors.password = '请输入密码'
    return false
  }

  if (loginForm.password.length < 3) {
    errors.password = '密码至少3个字符'
    return false
  }

  return true
}

const validateRegisterForm = () => {
  registerErrors.username = ''
  registerErrors.password = ''
  registerErrors.checkPassword = ''

  if (!registerForm.username.trim()) {
    registerErrors.username = '请输入用户名'
    return false
  }

  if (registerForm.username.length < 3) {
    registerErrors.username = '用户名至少3个字符'
    return false
  }

  if (!registerForm.password) {
    registerErrors.password = '请输入密码'
    return false
  }

  if (registerForm.password.length < 6) {
    registerErrors.password = '密码至少6个字符'
    return false
  }

  if (registerForm.password !== registerForm.checkPassword) {
    registerErrors.checkPassword = '两次输入的密码不一致'
    return false
  }

  return true
}

// 登录处理
const handleLogin = async () => {
  error.value = ''

  if (!validateLoginForm()) {
    return
  }

  try {
    loading.value = true
    const response = await userStore.login(loginForm)
    Message.success('登录成功')

    // 根据用户角色决定跳转路径
    let redirectPath = route.query.redirect as string
    
    // 直接从响应中获取用户类型，避免计算属性的时序问题
    const userType = response.data.userType
    const isAdmin = userType === 'admin'
    
    console.log('登录成功，用户类型:', userType, '是否管理员:', isAdmin)
    
    if (!redirectPath) {
      // 如果没有重定向路径，根据用户角色设置默认路径
      if (isAdmin) {
        redirectPath = '/admin'  // 管理员跳转到管理后台
      } else {
        redirectPath = '/'       // 普通用户跳转到首页
      }
    } else {
      // 如果有重定向路径，但用户是管理员且重定向路径不是管理员路径，则跳转到管理后台
      if (isAdmin && !redirectPath.startsWith('/admin')) {
        redirectPath = '/admin'
      }
    }
    
    console.log('准备跳转到:', redirectPath)
    router.push(redirectPath)
  } catch (err: any) {
    console.error('登录失败:', err)
    error.value = err.message || '用户名或密码错误，请重试'
    Message.error('登录失败')
  } finally {
    loading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  if (!validateRegisterForm()) {
    return
  }

  try {
    registerLoading.value = true
    await userRegister(registerForm)
    Message.success('注册成功，请登录')

    // 清空注册表单
    registerForm.username = ''
    registerForm.password = ''
    registerForm.checkPassword = ''
  } catch (err: any) {
    console.error('注册失败:', err)
    Message.error(err.message || '注册失败，请检查输入信息')
  } finally {
    registerLoading.value = false
  }
}
</script>

<style scoped>
.login-page {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.login-container,
.register-container {
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 30px;
}

.card-title {
  color: #333;
  font-weight: 600;
}

.input-group-text {
  background-color: #f8f9fa;
  border-right: none;
  color: #6c757d;
}

.form-control {
  border-left: none;
  box-shadow: none;
}

.form-control:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.input-group:focus-within .input-group-text {
  border-color: #007bff;
  background-color: rgba(0, 123, 255, 0.1);
}

.btn-primary {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  border: none;
  font-weight: 500;
  padding: 12px;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
}

.btn-success {
  background: linear-gradient(135deg, #28a745 0%, #218838 100%);
  border: none;
  font-weight: 500;
  padding: 12px;
}

.btn-success:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.required {
  color: #dc3545;
}

.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}

.alert {
  border: none;
  border-radius: 10px;
}

.form-check-input:checked {
  background-color: #007bff;
  border-color: #007bff;
}

.invalid-feedback {
  font-size: 0.875rem;
}

.is-invalid {
  border-color: #dc3545;
}

.is-invalid:focus {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}

@media (max-width: 768px) {
  .container {
    padding: 20px 15px;
  }

  .card-body {
    padding: 30px 20px !important;
  }
}
</style> 